/*

Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.s


*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;


 //Definition for singly-linked list.
 struct ListNode {
     int val;
    ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
	ListNode* rotateRight(ListNode* head, int k) {
		if (head == NULL || head->next == NULL )
		{
			return head;
		}
		
		int  len = 0;

		ListNode *p = new ListNode(-1);
		p->next = head;

		while (p->next !=NULL)
		{
			len++;
			p = p->next;
		}

		p->next = head;

		int index = len - k%len;

		for (int i = 0; i < index; i++)
		{
			p = p->next;
			head = head->next;

		}

		p->next = NULL;

		return head;


	}
};



int main(int argc, char*argv[])
{
	
	ListNode *head = new ListNode(-1);
	ListNode *cur = new ListNode(-1);
	cur = head;

	for (int  i = 1; i < argc; i++)
	{
		int temp = atoi(argv[i]);
		ListNode *p = new ListNode(temp);
		cur->next = p;
		cur = cur->next;
	}

	head = head->next;

	ListNode *result = new ListNode(-1);
	int k = 2;
	
	Solution s;
	
	result = s.rotateRight(head,k);


	system("pause");
	return 0;

}